# -*- coding: utf-8 -*-
import logging
import sys
from lxml import etree
from dateutil import parser
import time
from datetime import timedelta

import os
import requests
import traceback

# add up one level dir into sys path
from common.lottery.handler import crawl_from_opencai

sys.path.append(os.path.abspath(os.path.dirname(os.path.dirname(
    os.path.dirname(os.path.dirname(os.path.dirname(__file__)))))))
os.environ['DJANGO_SETTINGS_MODULE'] = 'base.settings'

from common.lottery.cyclical.tj_ssc.db.activity import fullfill_result
from common.lottery import LOTTERY_TYPE, OPENCAI_LOTTERY_TYPES
from common.timer import TIMER_EVENT_TYPE, TimerEvent
from common.utils import tz

# 500彩票网
URL_500 = 'http://kaijiang.500.com/static/info/kaijiang/xml/tjssc/%s.xml'

# 168开奖网
URL_168 = 'http://api.1680210.com/CQShiCai/getBaseCQShiCaiList.do?date=%s&lotCode=10003'


def _parse_and_fill_168(data, refer):
    if data['errorCode'] == 0:
        nodes = data['result']['data']
        for node in nodes:
            phase = node['preDrawIssue']
            number = node['preDrawCode'].replace(',', '')
            activity = fullfill_result(phase, number, refer)
            if activity:
                TimerEvent.submit(TIMER_EVENT_TYPE.CALC_STATS, {
                    'number': number, 'term': phase,
                    'activity_type': LOTTERY_TYPE.TJ_SSC}, tz.now_ts())
                TimerEvent.submit(TIMER_EVENT_TYPE.ACTIVITY_ANNOUNCE, {
                    'number': number, 'term': phase,
                    'activity_type': LOTTERY_TYPE.TJ_SSC}, tz.now_ts())


def _parse_and_fill(resp, refer):
    nodes = etree.fromstring(resp)
    for node in nodes:
        attrib = node.attrib
        phase = attrib['expect']
        number = attrib['opencode']
        number = ''.join(number.split(','))
        activity = fullfill_result(phase, number, refer)
        if activity:
            TimerEvent.submit(TIMER_EVENT_TYPE.CALC_STATS, {
                'number': number, 'term': phase,
                'activity_type': LOTTERY_TYPE.TJ_SSC}, tz.now_ts())
            TimerEvent.submit(TIMER_EVENT_TYPE.ACTIVITY_ANNOUNCE, {
                'number': number, 'term': phase,
                'activity_type': LOTTERY_TYPE.TJ_SSC}, tz.now_ts())


def crawl_history_from_168(date):
    url = URL_168 % date.strftime('%Y-%m-%d')
    try:
        response = requests.get(url, timeout=10)
    except Exception:
        raise
    if response.status_code != 200:
        raise RuntimeError('request error')
    _parse_and_fill_168(response.json(), url)


def crawl_history(date):
    url = URL_500 % date.strftime('%Y%m%d')
    try:
        response = requests.get(url, timeout=10)
    except Exception:
        raise
    if response.status_code != 200:
        raise RuntimeError('request error')
    _parse_and_fill(response.content, url)


''' 在cron里面每天北京时间凌晨1点跑头一天
'''


def crawl_newest(now=None):
    '''官网爬虫
    '''
    now = now or tz.local_now()
    refer = URL_500 % now.strftime('%Y%m%d')
    url = refer
    try:
        response = requests.get(url, timeout=5)
    except Exception:
        return now
    if response.status_code != 200:
        return now
    _parse_and_fill(response.content, refer)
    return None


def crawl_newest_from_168(now=None):
    now = now or tz.local_now()
    url = URL_168 % now.strftime('%Y-%m-%d')
    try:
        response = requests.get(url, timeout=5)
    except Exception:
        return now
    if response.status_code != 200:
        return now
    _parse_and_fill_168(response.json(), url)
    return None


def main(d):
    while True:
        try:
            crawl_from_opencai(LOTTERY_TYPE.TJ_SSC)
        except Exception as e:
            logging.exception(u'%s error: %s' % (OPENCAI_LOTTERY_TYPES.get(LOTTERY_TYPE.TJ_SSC), e))
        if d:
            break
        time.sleep(60)


if __name__ == '__main__':
    date = sys.argv[1] if len(sys.argv) > 1 else None
    main(date)
